/**
 * 
 */
package zkoran.qrfan;

import java.util.ArrayList;
import java.util.List;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 * Activity that shows details of the match, list of all fans and button to add new ones
 * 
 * @author zdenda
 */
public class MatchActivity extends Activity {
	
	private static final int NEW_FAN_REQUEST = 1;
	private static final int CONTEXTMENU_DELETE = 0;

	public static String EXTRAS_NAME = "name";
	
	private TextView mTextViewName;
	private Button mButtonScan, mButtonManually;
	private ListView mListViewFans;
	
	private List<String> mFans = new ArrayList<String>();
	private ArrayAdapter<String> mAdapter;
	
	private String mMatchName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.match);
		
		mTextViewName = (TextView) findViewById(R.id.textview_match_name);
		
		mMatchName = getIntent().getExtras().getString(EXTRAS_NAME);
		mTextViewName.setText(mMatchName);
		
		mButtonScan = (Button) findViewById(R.id.button_scan);
		mButtonScan.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				startScanActivity();
			}
		});
		
		
		mButtonManually = (Button) findViewById(R.id.button_manually);
		mButtonManually.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				startNewFanActivity();				
			}
		});
		
		
		mListViewFans = (ListView) findViewById(R.id.listView_fans);       
        
        mFans.addAll(MatchModel.getAllFans(mMatchName));
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mFans);
        mListViewFans.setAdapter(mAdapter);
        
        mListViewFans.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				menu.setHeaderTitle(R.string.contextMenu_fan_header);
				menu.add(Menu.NONE, CONTEXTMENU_DELETE, Menu.NONE, R.string.contextMenu_fan_delete);
				
			}
		});
		
		
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		// If the request went OK
		if(resultCode == Activity.RESULT_OK) {
			
			switch (requestCode) {
			case MatchActivity.NEW_FAN_REQUEST:
				
				Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
	    		refreshListViewFans();
				break;
				
			case IntentIntegrator.REQUEST_CODE:
				
				IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
				if(scanResult != null) {
					Toast.makeText(this, scanResult.getContents(), Toast.LENGTH_SHORT).show();
					String code = scanResult.getContents();
					if(!mFans.contains(code)) {
						MatchModel.addfan(mMatchName, code);
					} else {
						Toast.makeText(this, R.string.message_fan_exist_error, Toast.LENGTH_SHORT).show();
					}
					refreshListViewFans();
				}

			default:
				break;
			}
			
			
		}
		
    	/*
    	// If the request went OK and the request was NEW_MATCH_REQUEST
    	if(resultCode == RESULT_OK && requestCode == NEW_FAN_REQUEST) {
    		Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
    		mFans.clear();
    		mFans.addAll(MatchModel.getAllFans(mMatchName));
    		mAdapter.notifyDataSetChanged();
    	}
    	*/
	}
	
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo();
    	int position = menuInfo.position;
    	
    	switch (item.getItemId()) {
		case CONTEXTMENU_DELETE:
			showDialogYesNo(position);
			break;
			
		default:
			break;
		}
    	
    	return super.onContextItemSelected(item);
	}
	

	/**
	 * Starts new activity {@link NewFanActivity}
	 */
	protected void startNewFanActivity() {
		Intent intent = new Intent(this, NewFanActivity.class);
		intent.putExtra(EXTRAS_NAME, mMatchName);
		startActivityForResult(intent, NEW_FAN_REQUEST);		
	}
	
	/**
	 * Starts Barcode Scanner
	 */
	protected void startScanActivity() {
		IntentIntegrator integrator = new IntentIntegrator(this);
		integrator.initiateScan();
	}
	
	
	private void showDialogYesNo(final int position) {
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.alert_dialog_fan_delete_title)
		       .setCancelable(false)
		       .setPositiveButton(R.string.alert_dialog_positive, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   mFans.remove(position);
		        	   MatchModel.updateFans(mMatchName, mFans);
		        	   refreshListViewFans();
		           }
		       })
		       .setNegativeButton(R.string.alert_dialog_negative, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		
		AlertDialog alert = builder.create();
		alert.show();
		
	}
	
	
	/**
	 * Loads fresh data and notifies listView to refreshing
	 */
	private void refreshListViewFans() {
		
    	mFans.clear();
		mFans.addAll(MatchModel.getAllFans(mMatchName));
		mAdapter.notifyDataSetChanged();
		
	}

}
